import csv
import json

import pandas as pd


def json_to_csv(json_file, csv_file):
    """将JSON文件转换为CSV文件"""
    try:
        # 读取JSON文件
        with open(json_file, "r", encoding="utf-8") as f:
            data = json.load(f)

        if not data:
            print("JSON文件中没有数据")
            return

        # 使用pandas转换
        df = pd.DataFrame(data)

        # 保存为CSV
        df.to_csv(
            csv_file,
            sep=",",
            index=False,
            encoding="utf-8-sig",
            quotechar='"',
            quoting=csv.QUOTE_NONNUMERIC,
        )

        print(f"成功将 {len(data)} 条数据从 {json_file} 转换到 {csv_file}")

    except FileNotFoundError:
        print(f"错误：找不到文件 {json_file}")
    except Exception as e:
        print(f"转换过程中发生错误：{e}")


if __name__ == "__main__":
    # 输入JSON文件路径（你的临时数据文件）
    input_json = "temp_video_data.json"
    # 输出CSV文件路径
    output_csv = "bilibili_videos_from_json.csv"

    json_to_csv(input_json, output_csv)
